const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
// 终端列表
router.post('/app/getContactList', async ctx => {
    let tenantId= ctx.user.tenantId
    let uid= ctx.user.id
    let body= ctx.request.body
    let keyWord= body.keyWord?body.keyWord:''
    let lat= body.lat?body.lat:''
    let lon= body.lon?body.lon:''
    let goodCatId= body.goodCatId?body.goodCatId:''
    let sortByNear= body.sortByNear?body.sortByNear:false
    let isMy= body.isMy?body.isMy:false
    let currentPage= body.currentPage
    let pageSize= body.pageSize?body.pageSize:30
    let offset = (currentPage - 1) * pageSize;
    let sql = `select a.* from v_contact a   where a.tenantId=${tenantId}  `
    if(isMy) {
         sql = `select a.id,a.name,a.linkMobile,a.linkName,a.linkPhone,a.address,a.imgUrl,a.distance,
       a.longitude,a.latitude from v_contact a left join contact_sales b on a.tenantId=b.tenantId
         and a.id=b.buId  where a.tenantId=${tenantId} and b.salesId=${uid} `
    }
    if(keyWord) {
        sql += ` and (a.name like '%${keyWord}%' or a.pinYin like '%${keyWord}%') `
    }
    if(goodCatId) {
        sql += ` and a.contactCatId=${goodCatId} `
    }
    if(sortByNear) {
        sql += ` order by address,id `
    }
    else {
        sql += ` order by address,id `
    }
    sql += ` offset ${offset} rows fetch  next ${pageSize} rows only ;`
    let list = await db.query(sql,{type: QueryTypes})
    list.map(row => {
        row.locate = ''
        if(!row.longitude || !row.latitude) {
            row.locate = '未定位'
        }
    })
    return ctx.suc('', {
        total: 0,
        list
    })

})


module.exports = router;